package com.oocl.jmsbook.consumer.jms;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.jmsbook.consumer.dao.BookDao;
import com.oocl.jmsbook.consumer.impl.BookDaoImpl;
import com.oocl.jmsbook.pojo.Book;
import com.oocl.jmsbook.util.JMSUtil;

public class BookJMSReceiverThread implements Runnable {
	
	private static final Logger LOGGER = Logger.getLogger(BookJMSReceiverThread.class);

	@Override
	public void run() {
		Connection conn = JMSUtil.createConnection();
		Destination queue = JMSUtil.getQueue();
		Session sess = null;
		MessageConsumer consumer = null;
		ObjectMapper mapper = new ObjectMapper();
		BookDao bookDao = new BookDaoImpl();
		
		try {
			conn.start();
			sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			consumer = sess.createConsumer(queue);
			
			while (true) {
				TextMessage textMsg = (TextMessage) consumer.receive();
				Book b = mapper.readValue(textMsg.getText(), Book.class);
				LOGGER.info("Inserting book " + b.getId() + " into database...");
				bookDao.addBook(b);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			JMSUtil.close(null, consumer, sess, conn);
		}
		
	}
}
